﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using AloneLibrary.Services.Camera;

namespace NetworkStateManagement.Classes
{
    class EnvironmentHandler : DrawableGameComponent
    {
        List<GameObject> gameObjects;
        Matrix world = Matrix.Identity;
        ThirdPersonCamera camera;

        public EnvironmentHandler(Game game)
            : base(game)
        {
            this.gameObjects = new List<GameObject>();
        }

        protected override void LoadContent()
        {
            gameObjects.Add(new GameObject(Game.Content.Load<Model>(@"Models\Ground"), Vector3.Zero, Vector3.Zero, 0.1f));
            camera = (ThirdPersonCamera)Game.Services.GetService(typeof(ThirdPersonCamera));
          
            base.LoadContent();
        }

        public override void Draw(GameTime gameTime)
        {
            foreach (GameObject go in this.gameObjects)
            {
                Matrix[] transforms = new Matrix[go.Model.Bones.Count];

                go.Model.CopyAbsoluteBoneTransformsTo(transforms);

                world = Matrix.CreateScale(go.Scale)
                    * Matrix.CreateRotationY(go.Direction.Y)
                    * Matrix.CreateTranslation(go.Position);

                foreach (ModelMesh modmesh in go.Model.Meshes)
                {
                    foreach (BasicEffect effect in modmesh.Effects)
                    {
                        //effect.EnableDefaultLighting();
                        //effect.PreferPerPixelLighting = true;
                        effect.World = transforms[modmesh.ParentBone.Index] * world;
                        effect.Projection = camera.Projection;
                        effect.View = camera.View;
                    }
                    modmesh.Draw();
                }
            }
            base.Draw(gameTime);
        }
    }
}
